<?php
namespace Home\Controller;
use Lib\Api\AgentApi;
use Lib\Api\AgentCommissionSetApi;
use Lib\Api\GameTypeProfitApi;
use Lib\Api\OrderApi;
use Lib\Api\OrderCommissionApi;
use Lib\Api\RebateRatio;
use Lib\Api\RebateRatioApi;
use Lib\Api\SysApi;
use Lib\Api\UserApi;
use Lib\Api\UserBelongApi;
use Think\Controller;

class IndexController extends Controller {

    public function index() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        if (empty(session('user_id')) && empty(session("mobile_phone"))) {
            $this->display("login");
            exit;
        }
        if (empty(session("organization_code"))) {
            // 跳转选择公众号页面
            $mobile_phone = session("mobile_phone");
            $where['_string'] = "a.mobile_phone = '".$mobile_phone."' and d.id is not null";
            $left = "left join fs_user_belong b on b.user_id = a.id";
            $left .= " left join fs_organization c on c.id = b.organization_id";
            $left .= " left join fs_organization_setting d on d.organization_id = c.id";
            $users = UserApi::getListAllByCondition($where, $left, "a.id, a.balance, concat(c.p_code,c.level,c.code) as organization_code, d.name");

            for ($i=0; $i<count($users); $i++) {
                session("gzh_".$users[$i]["organization_code"], $users[$i]);
            }

            $this->assign('users', $users);
            $this->display("selectOrg");
            exit;
        }

        /*$is_set_password = 0;
        if (!empty(session("set_password"))) {
            $is_set_password = session("set_password");
        }*/

        $is_set_password = session("set_password");

        $user_id = session('user_id');
        $user = UserApi::getInfo(array("id"=>$user_id));
        if (!empty($user['mobile_phone'])) {
            $avatar = $user['photo_url'];
            $balance = $user['balance'];

            // 获取代金劵总数
            $modelObj = M('Voucher');
            $voucher_map['user_id'] = array('eq', $user['id']);
            $voucher_map['state'] = array('eq', 2);
            $voucher_map['DATE_FORMAT(end_date, "%Y-%m-%d")'] = array('egt', date('Y-m-d'));
            $couponnumber = $modelObj->where($voucher_map)->count('id');
        } else {
            $this->display("bind_mobile_phone");
            exit;
        }

        $sys = SysApi::getInfo(array("id"=>1), "invite_code_state, use_voucher, once_max_order_num, buy_interval_time");

        $week = getWeek();
        $model = M();
        $field = "a.*, b.contact,b.profit_rate, c.close_value as zuoshou, c.open_value as jingkai, c.max_value as high, c.min_value as low, d.value as bid";
        $list = $model->table('fs_game_type a')
            ->join('left join fs_game_type_profit b on b.type = a.id')
            ->join('left join fs_day_info c on c.game_type = a.id')
            ->join('left join fs_temp_data d on d.type = a.id')
            //->field('r.name, sm.name, m.id')
            ->field($field)
            ->where(array('a.state'=>1))
            ->order('a.sort asc,b.sort asc')
            ->select();


        $order_list = OrderApi::getList(array("user_id"=>session("user_id"), "state"=>0), "", 1, 99999, "a.order_no, a.play_name, a.play_type, a.type, a.mun as num, a.order_contact, a.open_price, a.begin_time", "begin_time desc");

        $game_arr = Array();
        for ($i=0; $i<count($list); $i++) {
            $is_flag = true;
            for ($j=0; $j<count($game_arr); $j++) {
                if ($game_arr[$j]['id'] == $list[$i]['id']) {
                    $is_flag = false;
                }
            }
            if($is_flag == true) {
                $time = date('Y-m-d H:i');
                $game_type["id"] = $list[$i]["id"];
                $game_type["game_name"] = $list[$i]["show_name"];
                $game_type["code"] = $list[$i]["name_code"];
                $game_type["norms"] = $list[$i]["norms"];
                $game_type["low"] = $list[$i]["low"];
                $game_type["high"] = $list[$i]["high"];
                $game_type["zuoshou"] = $list[$i]["zuoshou"];
                $game_type["jingkai"] = $list[$i]["jingkai"];
                $game_type["bid"] = $list[$i]["bid"];
                $game_type["last_time_f"] = $time;
                $game_type["money_list"] = '500,100,10';
                $game_type["decimal_digit"] = $list[$i]["value_length"];
                $game_type["max_num"] = $sys['once_max_order_num'];
                $game_type["contact_list"] = array();

                $position_order_arr = array();
                if (!empty($order_list)) {
                    for ($j=0; $j<count($order_list); $j++) {
                        if ($order_list[$j]['play_type'] == $list[$i]["id"]) {
                            $position_order['order_no'] = $order_list[$j]['order_no'];
                            $position_order['play_name'] = $order_list[$j]['play_name'];
                            $position_order['type'] = $order_list[$j]['type'];
                            $position_order['num'] = $order_list[$j]['num'];
                            $position_order['order_contact'] = $order_list[$j]['order_contact'];
                            $position_order['open_price'] = $order_list[$j]['open_price'];
                            $position_order['begin_time'] = $order_list[$j]['begin_time'];
                            array_push($position_order_arr, $position_order);
                        }
                    }
                }

                // var_dump($list[$i]["id"]);
                $game_type["position_order"] = $position_order_arr;

                $after_slide = $sys['buy_interval_time'];
                $buy_act_time = 0;
                if (count($order_list) > 0) {
                    $order_time = $order_list[0]['begin_time'];
                    $begin_time = date('Y-m-d H:i:s',strtotime("$order_time +$after_slide second"));
                    $cle = strtotime($begin_time) - strtotime(date('Y-m-d H:i:s')); //得出时间戳差值
                    $buy_act_time=$cle;
                    if ($buy_act_time < 0) {
                        $buy_act_time = 0;
                    }
                }
                $game_type["buy_act_time"] = $buy_act_time;

                if ($list[$i][$week] == 1) {
                    $open_time_temp = date('Y-m-d') . " " . $list[$i]['open_time'];
                    $close_time_temp = date('Y-m-d') . " " . $list[$i]['close_time'];
                    $open_time = strtotime($open_time_temp);
                    $close_time = strtotime($close_time_temp);
                    $time = time();

                    if ($time>=$close_time && $time<=$open_time) {
                        $game_type["isRest"] = 2;
                    } else {
                        $game_type["isRest"] = 1;
                    }
                } else {
                    $game_type["isRest"] = 2;
                }

                $limit = 30;
                $map['game_type'] = $list[$i]["id"];
                $modelName = 'Minute';
                $modelObj = M($modelName);
                $date_arr = $modelObj->field('open_value,close_value,max_value,min_value,DATE_FORMAT(create_date, "%Y-%m-%d %H:%i") time')->where($map)->page(0, $limit)->order('create_date desc')->select();//page两个参数（页码，条数），不需要自己计算

                $data_list = array();
                for ($z=(count($date_arr)-1); $z>=0;$z--) {
                    $data_list_obj["open_value"] = $date_arr[$z]['open_value'];
                    $data_list_obj["close_value"] = $date_arr[$z]['close_value'];
                    $data_list_obj["max_value"] = $date_arr[$z]['max_value'];
                    $data_list_obj["min_value"] = $date_arr[$z]['min_value'];
                    $data_list_obj["begin_time"] = $date_arr[$z]['time'];
                    $data_list_obj["time"] = $date_arr[$z]['time'];
                    array_push($data_list, $data_list_obj);
                }

                $temp_modelName = 'TempData';
                $temp_modelObj = M($temp_modelName);
                $temp_list = $temp_modelObj->field("value")->where(array("type"=>$list[$i]["id"]))->find();
                $data_list_obj["open_value"] = $temp_list['value'];
                $data_list_obj["close_value"] = $temp_list['value'];
                $data_list_obj["max_value"] = $temp_list['value'];
                $data_list_obj["min_value"] = $temp_list['value'];
                $data_list_obj["begin_time"] = date('Y-m-d H:i');
                $data_list_obj["time"] = date('Y-m-d H:i');
                array_push($data_list, $data_list_obj);

                $game_type["data_list"] = array(
                    "M1"=>array("name"=>"今日走势","key"=>"M1", "value"=>1, "type"=>"l", "list"=>$data_list),
                    "M15"=>array("name"=>"15分钟K线","key"=>"M15", "value"=>15, "type"=>"k","list"=>array()),
                    "M30"=>array("name"=>"30分钟K线","key"=>"M30", "value"=>30,"type"=>"k", "list"=>array()),
                    "M60"=>array("name"=>"60分钟K线","key"=>"M60", "value"=>60,"type"=>"k", "list"=>array()),
                );


                array_push($game_arr, $game_type);
            }
        }

        for ($i=0; $i<count($list); $i++) {
            for ($j=0; $j<count($game_arr); $j++) {
                if ($game_arr[$j]['id'] == $list[$i]['id']) {
                    $time_list_obj["contact"] = $list[$i]["contact"];
                    $time_list_obj["profit_rate"] = $list[$i]["profit_rate"];
                    array_push($game_arr[$j]["contact_list"], $time_list_obj);
                }
            }
        }

        /*$time_group = 16;
        $limit = $time_group*29 + ($time_group-1);
        $modelName = 'Minute';
        $modelObj = M($modelName);
        for ($j=0; $j<count($game_arr); $j++) {
            $map['game_type'] = $game_arr[$j]['id'];
            $list = $modelObj->field('open_value,close_value,max_value,min_value,DATE_FORMAT(create_date, "%Y-%m-%d %H:%i") time')->where($map)->page(0, $limit)->order('create_date desc')->select();//page两个参数（页码，条数），不需要自己计算
            for ($i=(count($list)-1); $i>=0;$i--) {
                $data_list_obj["open_value"] = $list[$i]['open_value'];
                $data_list_obj["close_value"] = $list[$i]['close_value'];
                $data_list_obj["max_value"] = $list[$i]['max_value'];
                $data_list_obj["min_value"] = $list[$i]['min_value'];
                $data_list_obj["time"] = $list[$i]['time'];
                array_push($game_arr[$j]["data_list"], $data_list_obj);
            }

            $temp_modelName = 'TempData';
            $temp_modelObj = M($temp_modelName);
            $temp_list = $temp_modelObj->field("value")->where(array("type"=>$game_arr[$j]['id']))->find();

            $data_list_obj["open_value"] = $temp_list['value'];
            $data_list_obj["close_value"] = $temp_list['value'];
            $data_list_obj["max_value"] = $temp_list['value'];
            $data_list_obj["min_value"] = $temp_list['value'];
            $data_list_obj["time"] = date('Y-m-d H:i');
            array_push($game_arr[$j]["data_list"], $data_list_obj);
        }*/

        $this->assign('invite_code_state', $sys['invite_code_state']);
        $this->assign('use_voucher', $sys['use_voucher']);
        $this->assign('is_set_password', $is_set_password);
        $this->assign('avatar', $avatar);
        $this->assign('balance',$balance);
        $this->assign('couponnumber', $couponnumber);
        $this->assign('games', json_encode($game_arr));
        // $this->assign('open_pc', check_wap());
        $this->display();
    }

    public function select_gzh() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $organization_code = $_POST['organization_code'];
        if (!empty(session("gzh_".$organization_code))) {
            $session_user = session("gzh_".$organization_code);

            $user['login_num'] = array('exp','login_num+1');
            $user['last_login'] = date('Y-m-d H:i:s');
            $user['login_ip'] = getenv('REMOTE_ADDR');
            UserApi::saveByCondition(array("id"=>$session_user["id"]), $user);

            session("user_id", $session_user["id"]);
            session("organization_code", $session_user["organization_code"]);

            $data['code'] = 1;
        } else {
            $data['code'] = -1;
            $data['msg'] = '公会号错误';
        }
        $this->ajaxReturn($data);
    }

    public function checktrade() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $game_type = $_POST['game_type'];
        $user_id = session('user_id');

        $modelObj = M("Sys");
        $sys = $modelObj->field("use_voucher")->where(array('id' => 1))->find();

        if ($sys['use_voucher'] == 1) {
            $model = M();
            $field = "a.voucher_range,a.money,b.name,b.use_money,b.type";
            $map['a.user_id'] = $user_id;
            $map['a.state'] = 2;
            $map['DATE_FORMAT(a.start_date, "%Y-%m-%d")'] = array('elt', date('Y-m-d'));
            $map['DATE_FORMAT(a.end_date, "%Y-%m-%d")'] = array('egt', date('Y-m-d'));
            $list = $model->table('fs_voucher a')
                ->join('left join fs_voucher_type b on b.id = a.type')
                //->field('r.name, sm.name, m.id')
                ->field($field)
                ->where($map)
                ->select();

            if (count($list) > 0) {
                $data = array();
                $arr['status'] = 'ok';
                for ($i=0;$i<count($list);$i++) {
                    $is_add = true;
                    if ($list[$i]['voucher_range'] == 0) {
                        for ($j=0; $j<count($data); $j++) {
                            if ($data[$j]['money'] == $list[$i]['money'] && $data[$j]['type'] == $list[$i]['type']) {
                                $data[$j]["totals"] = $data[$j]["totals"]+1;
                                $is_add = false;
                            }
                        }
                    } else {
                        $voucher_range = explode(",",$list[$i]['voucher_range']);
                        for ($j=0;$j<count($voucher_range);$j++) {
                            if ($voucher_range[$j] == $game_type) {
                                for ($z=0; $z<count($data); $z++) {
                                    if ($data[$z]['money'] == $list[$i]['money'] && $data[$z]['type'] == $list[$i]['type']) {
                                        $data[$z]["totals"] = $data[$z]["totals"]+1;
                                        $is_add = false;
                                    }
                                }
                            }
                        }
                    }

                    if ($is_add == true) {
                        $voucher['name'] = $list[$i]['name'];
                        $voucher['money'] = $list[$i]['money'];
                        $voucher['type'] = $list[$i]['type'];
                        $voucher['use_money'] = $list[$i]['use_money'];
                        $voucher['totals'] = 1;
                        $voucher['can_user_num'] = 1;
                        $voucher['message'] = '';
                        array_push($data, $voucher);
                    }
                }
                $arr['list'] = $data;
            } else {
                $arr['status'] = 'no';
            }
        } else {
            $arr['status'] = 'no';
        }

        $arr['Success'] = $this->isClose($game_type);

        /*$modelObj = M("Sys");
        $sys = $modelObj->field("buy_interval_time")->where(array('id' => 1))->find();
        $after_slide = $sys['buy_interval_time'];*/

        /*$begin_time = date('Y-m-d H:i:s');
        $begin_time = date('Y-m-d H:i:s',strtotime("$begin_time -$after_slide second"));

        $modelName = 'Order';
        $modelObj = M($modelName);
        $order_map['user_id'] = array('eq',session('user_id'));
        $order_map['_string'] = 'begin_time > "'.$begin_time.'"';

        $list = $modelObj->field("begin_time")->where($order_map)->group('begin_time')->select();*/

        /*$order_list = OrderApi::getList(array("user_id"=>session("user_id"), "play_type"=>$game_type, "state"=>0), "", 1, 1, "a.begin_time", "begin_time desc");
        // $game_type["position_order"] = $order_list[0];

        $buy_btn_act_time = 0;
        if (count($order_list) > 0) {
            $order_time = $order_list[0]['begin_time'];
            $begin_time = date('Y-m-d H:i:s',strtotime("$order_time +$after_slide second"));
            $cle = strtotime($begin_time) - strtotime(date('Y-m-d H:i:s')); //得出时间戳差值
            $buy_btn_act_time=$cle;
        }
        $arr['buy_btn_act_time'] = $buy_btn_act_time;*/

        $this->ajaxReturn($arr);
    }

    // 用户下单
	public function dealOrder() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $user_id = session('user_id');

        $user = UserApi::getInfo(array("id"=>$user_id), "is_deall_order");
        $org_state = UserBelongApi::getAllUserBelongList(array("a.user_id"=>$user_id, "a.state"=>1), "left join fs_customer b on b.organization_id = a.organization_id", "b.state");
        if ($user["is_deall_order"] == 2) {
            $arr['msg'] = "帐号不能下单！";
            $arr['success'] = 0;
            $this->ajaxReturn($arr);
            exit;
        } else {
            for ($i=0; $i<count($org_state); $i++) {
                if ($org_state[$i]['state'] == 2) {
                    $arr['msg'] = "帐号不能下单！";
                    $arr['success'] = 0;
                    $this->ajaxReturn($arr);
                    exit;
                }
            }
        }

        $play_type = 1;
        $type = 1;
        $arr = array();
        $real_price = 0;
        $is_judge_money = true;
        // $order_price = 0;
        $play_name = "--";
        $name_code = "";
        $norms = "";
        $num = 1;
        $order_contact = 0;
        $profit_rate = 100;

        if (!empty($_POST['order_contact']))  {
            $order_contact = $_POST['order_contact'];
        }

        if (!empty($_POST['play_type']) && intval($_POST['play_type']) > 0)  {
            $play_type = $_POST['play_type'];
        }
        if (!empty($_POST['play_name']))  {
            $play_name = $_POST['play_name'];
        }
        if (!empty($_POST['norms'])) {
            $norms = $_POST['norms'];
        }
        if (!empty($_POST['name_code'])) {
            $name_code = $_POST['name_code'];
        }
        if (!empty($_POST['num']) && intval($_POST['num']) > 0)  {
            $num = $_POST['num'];
        }

        // 写统一接口判断当前币种是否处理休盘状态
        if ($this->isClose($play_type) == false) {
            $arr['msg'] = "当前币种已休盘！";
            $arr['success'] = 0;
            $this->ajaxReturn($arr);
            exit;
        }

        // 风控判断
        // 获取用户所属会员单位
        $AGENTCONFIG = C('AGENTCONFIG');
        $level = 0;
        for($i = 0; $i<count($AGENTCONFIG); $i++) {
            if ($AGENTCONFIG[$i]["type"] == "dl") {
                $level = $AGENTCONFIG[$i]["level"];
            }
        }
        $where["a.user_id"] = array("eq", $user_id);
        $where["a.organization_level"] = array("eq", $level);
        $where['DATE_FORMAT(a.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');
        $left = "left join fs_organization b on b.id = a.organization_id";
        $left .= " left join fs_organization_statistics c on c.organization_id = a.organization_id and c.state = 2 and (DATE_FORMAT(c.begin_time, '%Y-%m-%d %H:%i:%s') <= '".date("Y-m-d H:i:s")."' and DATE_FORMAT(c.end_time, '%Y-%m-%d %H:%i:%s') >= '".date("Y-m-d H:i:s")."')";
        $organization = UserBelongApi::getUserBelongOrgByCondition($where, $left, "b.*, c.begin_balance, c.recharge, c.withdrawals");
        if (!empty($organization)) {
            // 当前风险率 = 会员单位当前余额/(会员单位当日初始金额+会员单位当日充值总金额-会员单位当日提现总金额)*100
            $organization_begin_balance = $organization["begin_balance"]+$organization["recharge"]-$organization["withdrawals"];
            if ($organization_begin_balance < 0) {
                // $organization_begin_balance = 0;
                $arr['msg'] = "当前不能下单";
                $arr['success'] = 0;
                $this->ajaxReturn($arr);
                exit;
            }

            $organization_balance = $organization["balance"];
            if ($organization_balance < 0) {
                $organization_balance = 0;
            }
            $risk_control_rate = $organization_balance/($organization_begin_balance)*100;
            if ($risk_control_rate < $organization["risk_control_rate"]) {
                $arr['msg'] = "当前不能下单";
                $arr['success'] = 0;
                $this->ajaxReturn($arr);
                exit;
            }
        }

        $gameTypeProfitList = GameTypeProfitApi::getList(array("type"=>$play_type));
        if ($order_contact != 0) {
            $f = true;
            for ($i=0;$i<count($gameTypeProfitList);$i++) {
                if ($order_contact == $gameTypeProfitList[$i]['contact']) {
                    $profit_rate = $gameTypeProfitList[$i]['profit_rate'];
                    $f = false;
                    break;
                }
            }
            if($f == true) {
                $order_contact = $gameTypeProfitList[0]['contact'];
                $profit_rate = $gameTypeProfitList[0]['profit_rate'];
            }
        } else {
            $order_contact = $gameTypeProfitList[0]['contact'];
            $profit_rate = $gameTypeProfitList[0]['profit_rate'];
        }


        $modelObj = M("Sys");
        $sys = $modelObj->field("max_order_money, min_order_money, use_voucher, once_max_order_num, order_fee, buy_interval_time")->where(array('id' => 1))->find();
        if ($num > $sys['once_max_order_num']) {
            $num = $sys['once_max_order_num'];
        }
        $voucher_price = 0;
        $juan_ids = array();
        if (!empty($_POST['juan_type']) && $sys['use_voucher'] == 1) {
            // 处理代金劵
            $juan_name = $_POST['juan_name'];
            $juan_type = $_POST['juan_type'];
            $can_use_juan_num = $_POST['can_use_juan_num'];
            $juan_money = $_POST['juan_money'];

            if ($juan_type == 1) {
                $is_judge_money = false;
            }

            $model = M();
            $field = "a.id,a.voucher_range,a.money,b.use_money";
            $map['a.user_id'] = $user_id;
            $map['a.money'] = $juan_money;
            $map['a.state'] = 2;
            $map['b.type'] = $juan_type;
            $map['DATE_FORMAT(a.start_date, "%Y-%m-%d")'] = array('elt', date('Y-m-d'));
            $map['DATE_FORMAT(a.end_date, "%Y-%m-%d")'] = array('egt', date('Y-m-d'));
            $list = $model->table('fs_voucher a')
                ->join('left join fs_voucher_type b on b.id = a.type')
                ->field($field)
                ->where($map)
                ->page(0, $can_use_juan_num)
                ->order('a.end_date asc')
                ->select();

            if (count($list) > 0) {
                for ($i=0; $i<count($list); $i++) {
                    if ($list[$i]['voucher_range'] == 0) {
                        $voucher_price += $list[$i]['money'];
                        array_push($juan_ids, $list[$i]['id']);
                    } else {
                        $voucher_range = explode(",",$list[$i]['voucher_range']);
                        for ($j=0;$j<count($voucher_range);$j++) {
                            if ($voucher_range[$j] == $play_type) {
                                $voucher_price += $list[$i]['money'];
                                array_push($juan_ids, $list[$i]['id']);
                            }
                        }
                    }
                }
            } else {
                $arr['msg'] = "没有找到可用的".$juan_name."！";
                $arr['success'] = 0;
                $this->ajaxReturn($arr);
                exit;
            }
        }

        if ($is_judge_money == true) {
            if (empty($_POST['order_price']) || floatval($_POST['order_price']) <= 0)  {
                $arr['msg'] = "你的下注金额呢？";
                $arr['success'] = 0;
                $this->ajaxReturn($arr);
                exit;
            } else if (floatval($_POST['order_price']) < $sys['min_order_money'] || floatval($_POST['order_price']) > $sys['max_order_money']) {
                $arr['msg'] = "下注金额太大或太小了！";
                $arr['success'] = 0;
                $this->ajaxReturn($arr);
                exit;
            } else {
                $real_price = $_POST['order_price'];
            }

            /*$real_price = $real_price*$num-$voucher_price;
            if ($real_price < 0) {
                $real_price = 0;
            }*/
            $modelName = 'User';
            $modelObj = M($modelName);
            $user_data = $modelObj->field("balance, id")->where(array('id' => session('user_id')))->find();
            if ($user_data['balance'] < ($real_price*$num)) {
                $arr['msg'] = "您的余额不足，请先充值！";
                $arr['success'] = -1;
                $this->ajaxReturn($arr);
                exit;
            }
        }

        if (!empty($_POST['type']))  {
            $type = $_POST['type'];
        }
        if ($type <= 0) {
            $type = 2;
        }

        $begin_time = date("Y-m-d H:i:s");// $this->get_order_date();

        $modelName = 'TempData';
        $modelObj = M($modelName);
        $temp_data = $modelObj->field("value")->where(array('type' => $play_type))->select();
        if (empty($temp_data) || count($temp_data) == 0) {
            $arr['msg'] = "下单失败，请重试";
            $arr['success'] = 0;
            $this->ajaxReturn($arr);
            exit;
        }
        $open_price = $temp_data[0]['value'];

        if (empty($_POST['order_no'])) {
            $order_no = $this->generate_order_no();
        } else {
            $order_no = $_POST['order_no'];
        }

        $order_fee = $sys['order_fee'];
        $order_price = $real_price*$num;
        $params = array("order_no"=>$order_no, "user_id"=>"$user_id", "play_type"=>"$play_type", "play_name"=>$play_name, "name_code"=>$name_code, "norms"=>$norms , "profit_rate"=>$profit_rate, "type"=>$type,
            "mun"=>$num, "order_price"=>"$order_price", "real_price"=>"$real_price", "voucher_price"=>$voucher_price, "order_contact"=>$order_contact,
            "open_price"=>"$open_price", "state"=>0, "state_to"=>0, "operate_type"=>1, "order_fee"=>$order_fee, "begin_time"=>$begin_time);
        $modelObj = M("Order");
        $result = $modelObj->add($params);

        if ($result > 0) {

            // 处理抵扣劵?
            if(count($juan_ids) > 0) {
                $modelObj = M('Voucher');
                $voucher_data['state'] = 1;
                $voucher_map['id'] = array('exp', ' IN ('.implode(',',$juan_ids).')');
                $modelObj->where($voucher_map)->save($voucher_data);
            }

            // 更新用户金额
            $balance = $real_price*$num-$voucher_price;
            $modelObj = M("User");
            $user_data['balance'] = array('exp','balance-'.$balance);
            $user_data['freeze_balance'] = array('exp','freeze_balance+'.$balance);//"freeze_balance+".$order_price;
            $modelObj->save($user_data);
            $user_data = $modelObj->where("id=$user_id")->field('balance')->find();
            $user_balance = $user_data['balance'];

            // 添交易记录
            $modelObj = M("TradeDetail");
            $params = array("user_id"=>$user_id, "deal_user_id"=>0, "out_trade_no"=>"$order_no", "type"=>1,
                "money"=>$balance, "fee_money"=>0, "other_money"=>$voucher_price,"balance"=>$user_balance,
                "source"=>1,"state"=>1, "datetime"=>date('Y-m-d H:i:s'));
            $modelObj->add($params);

            // 添加经纪人返拥信息
            $agent_map['c.id'] = $user_id;
            $agent_map['a.game_type'] = $play_type;
            $agent_map['b.state'] = 1;
            $agent_map['DATE_FORMAT(a.take_effect_time, "%Y-%m-%d %H:%i:%s")'] = array("elt", "DATE_FORMAT('".$begin_time."', '%Y-%m-%d %H:%i:%s')");
            $left = "left join fs_agent b on b.id = a.agent_id";
            $left .= " left join fs_user c on c.recommend_id = b.id";
            $field = 'a.commission_ratio, b.id as agent_id';
            $agentCommissionSet = AgentCommissionSetApi::geInfoByCondition($agent_map, $left, $field, 'a.take_effect_time desc');

            $orderCommission_arr = array();
            if (!empty($agentCommissionSet)) {
                $orderCommission['order_id'] = $result;
                $orderCommission['agent_id'] = $agentCommissionSet["agent_id"];
                $orderCommission['commission_level'] = 0;
                $orderCommission['commission_ratio'] = $agentCommissionSet["commission_ratio"];
				$orderCommission['commission_money'] = 0;
                $orderCommission['state'] = 2;
                $orderCommission['datetime'] = date("Y-m-d H:i:s");
                array_push($orderCommission_arr, $orderCommission);

                $rebateRatio = RebateRatioApi::getRebateRatioByCondition(array("game_type"=>$play_type), "rebate_level, rebate_ratio");
                if (!empty($rebateRatio)) {
                    $agent_id = $agentCommissionSet["agent_id"];
                    // var_dump($agent_id);
                    for ($i=0; $i<count($rebateRatio); $i++) {
                        if ($agent_id > 0) {
                            $left = "left join fs_user b on b.agent_id = a.id";
                            $agent = AgentApi::getInfo(array("a.id"=>$agent_id), $left, "b.recommend_id");
                            if (!empty($agent) && $agent["recommend_id"] > 0 && $rebateRatio[$i]['rebate_ratio'] > 0) {
                                $orderCommission['order_id'] = $result;
                                $orderCommission['agent_id'] = $agent["recommend_id"];
                                $orderCommission['commission_level'] = $rebateRatio[$i]['rebate_level'];
                                $orderCommission['commission_ratio'] = $rebateRatio[$i]["rebate_ratio"];
                                $orderCommission['state'] = 2;
                                $orderCommission['datetime'] = date("Y-m-d H:i:s");
                                array_push($orderCommission_arr, $orderCommission);
                                $agent_id = $agent["recommend_id"];
                            }

                            /*$left = "left join fs_user b on b.agent_id = a.id";
                            $left .= " left join fs_agent c on c.id = b.recommend_id";
                            $left .= " left join fs_user d on d.agent_id = c.id";
                            $agent = AgentApi::getInfo(array("a.id"=>$agent_id), $left, "c.id, d.recommend_id");
                            if (!empty($agent)) {
                                $orderCommission['order_id'] = $result;
                                $orderCommission['agent_id'] = $agent["id"];
                                $orderCommission['commission_level'] = $rebateRatio[$i]['rebate_level'];
                                $orderCommission['commission_ratio'] = $rebateRatio[$i]["rebate_ratio"];
                                $orderCommission['state'] = 2;
                                $orderCommission['datetime'] = date("Y-m-d H:i:s");
                                array_push($orderCommission_arr, $orderCommission);
                                $agent_id = $agent["recommend_id"];
                            }*/
                        }
                    }
                }
            }
            if (count($orderCommission_arr) > 0) {
                OrderCommissionApi::addAll($orderCommission_arr);
            }

            // $arr['begin_time'] = date('Y/m/d H:i:s', strtotime("$begin_time +0 second"));
            // $arr['end_time'] = date('Y/m/d H:i:s',strtotime("$begin_time +$trade_time second"));

            /*$i_time = date("i", time($begin_time));
            $second = date("s", time($begin_time));
            $arr['time'] = $i_time.':'.$second;*///($second+1);

            $arr['success'] = 1;
            // $arr['open_price'] = $open_price;
            // $arr['money'] = $order_price;

            $after_slide = $sys['buy_interval_time'];
            $order_time = date('Y-m-d H:i:s',strtotime("$begin_time +$after_slide second"));
            $cle = strtotime($order_time) - strtotime(date('Y-m-d H:i:s')); //得出时间戳差值

            $arr['buy_act_time'] = $cle;
            $arr['open_price'] = $open_price;

            $arr['order_no'] = $order_no;
            $arr['user_id'] = $user_id;
            $arr['user_money'] = $user_balance;
            $arr['msg'] = "下单成功";
            $this->ajaxReturn($arr);
        } else {
            $arr['success'] = 0;
            $this->ajaxReturn($arr);
        }
    }

    public function getLotteryOrder() {
		$url = userState();
        if ($url != false) {
            $this->success('',$url);
        }
        $MAINTAIN = C('__MAINTAIN__');
        if ($MAINTAIN == true) {
            session("user_id", null);
            session("mobile_phone", null);
            session("organization_code", null);
            exit("系统维护中");
        }

        $order_no = $_POST['order_no'];
        $map['order_no'] = $order_no;
        $model = M();
        $field = "a.gain_price, a.real_price, a.state, a.close_price, a.open_price, a.order_price, b.game_name, a.order_no";
        $data = $model->table('fs_order a')
            ->join('left join fs_game_type b on b.id = a.play_type')
            ->field($field)
            ->where($map)
            ->find();

        $ajaxdata['order'] = $data;

        $modelName = 'User';
        $modelObj = M($modelName);
        $data = $modelObj->field('balance')->where(array('id' => session('user_id')))->find();

        $ajaxdata['user_money'] = $data['balance'];

        $this->ajaxReturn($ajaxdata);
    }

    // 生成订单编号
    private function generate_order_no() {
        $order_no = date('YmdHi').session('user_id').rand_number(1, 99);

        $modelName = 'Order';
        $modelObj = M($modelName);
        $map['order_no'] = $order_no;
        $list = $modelObj->where($map)->select();
        if (count($list) > 0) {
            return $this->generate_order_no();
        } else {
            return $order_no;
        }
    }

    // 获取下单时间
    private function get_order_date() {
        $after_slide = C("__AFTERSLIDE__");

        $begin_time = date('Y-m-d H:i:s');
        $end_time = date('Y-m-d H:i:s',strtotime("$begin_time +$after_slide second"));

        $modelName = 'Order';
        $modelObj = M($modelName);
        // $map['begin_time'] = array('egt',$begin_time);
        // $map['begin_time'] = array('elt',$end_time);

        $map['_string'] = 'begin_time >= "'.$begin_time.'" AND begin_time <= "'.$end_time.'"';

        $list = $modelObj->field("count(id) as num, begin_time")->where($map)->group('begin_time')->select();
        $temp_date = $end_time;
        $new_list = array();
        while (strtotime($temp_date) > strtotime($begin_time)) {
            $num = 0;
            for ($i=0;$i<count($list);$i++) {
                if(strtotime($temp_date) == strtotime($list[$i]["begin_time"])) {
                    $num = $list[$i]["num"];
                }
            }
            $obj['num'] = $num;
            $obj['begin_time'] = $temp_date;
            array_push($new_list, $obj);
            $temp_date = date('Y-m-d H:i:s',strtotime("$temp_date -1 second"));
        }
        $order_date = date('Y-m-d H:i:s');
        $index = count($new_list) - 1;
        for ($i=0;$i<count($new_list);$i++) {
            if($new_list[$index]['num'] == 0) {
                $order_date = $new_list[$index]['begin_time'];
                break;
            }
            $index--;
        }
        return $order_date;
    }

    // 判断币种是否已休盘
    private function isClose($game_type) {
        $week = getWeek();
        $modelName = 'Game_type';
        $modelObj = M($modelName);
        $map['id'] = $game_type;
        $dataModel = $modelObj->where($map)->find();
        if ($dataModel[$week] == 1) {

            $open_time_temp = date('Y-m-d') . " " . $dataModel['open_time'];
            $close_time_temp = date('Y-m-d') . " " . $dataModel['close_time'];
            $open_time = strtotime($open_time_temp);
            $close_time = strtotime($close_time_temp);
            $time = time();

            if ($time>=$close_time && $time<=$open_time) {
                return false;
            } else {
                return true;
            }
        } else {
            // 当前货币已休盘
            return false;
        }
    }
}